package com.cat.yygh.order.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cat.yygh.common.exception.YyghException;
import com.cat.yygh.enums.OrderStatusEnum;
import com.cat.yygh.enums.PaymentStatusEnum;
import com.cat.yygh.hospe.client.ScheduleFeignClient;
import com.cat.yygh.model.order.OrderInfo;
import com.cat.yygh.model.order.PaymentInfo;
import com.cat.yygh.model.user.Patient;
import com.cat.yygh.mq.MqConst;
import com.cat.yygh.mq.RabbitService;
import com.cat.yygh.order.mapper.OrderInfoMapper;
import com.cat.yygh.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cat.yygh.order.service.PaymentService;
import com.cat.yygh.order.service.WeiPayService;
import com.cat.yygh.order.util.HttpRequestHelper;
import com.cat.yygh.user.client.PatientFeignClient;
import com.cat.yygh.vo.hosp.ScheduleOrderVo;
import com.cat.yygh.vo.msm.MsmVo;
import com.cat.yygh.vo.order.OrderCountQueryVo;
import com.cat.yygh.vo.order.OrderCountVo;
import com.cat.yygh.vo.order.OrderMqVo;
import com.cat.yygh.vo.order.OrderQueryVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-11-27
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private ScheduleFeignClient scheduleFeignClient;
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private WeiPayService weiPayService;
    @Autowired
    private PaymentService paymentService;

    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //1.先根据scheduleId获取医生排班信息
        ScheduleOrderVo scheduleOrderVo = scheduleFeignClient.getScheduleById(scheduleId);
        //2.先根据patientId获取就诊人信息
        Patient patient = patientFeignClient.getPatient(patientId);
        //判断一下时间是否以及超过截至时间
        if (new DateTime(scheduleOrderVo.getStopTime()).isBeforeNow()){
            throw new YyghException(20001,"超过了挂号截止时间");
        }
        //3.从平台请求第三方医院，确认用户是否能挂号
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",scheduleOrderVo.getHoscode());
        paramMap.put("depcode",scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime",scheduleOrderVo.getReserveTime());
        paramMap.put("amount",scheduleOrderVo.getAmount());//挂号费用
        //使用httpclient发送请求，请求医院接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
        OrderInfo orderInfo = new OrderInfo();
        if (result != null && result.getInteger("code") == 200){
            //3.2如果返回能挂号，就把取出医生排班信息，就诊人信息及其第三方医院返回的信息都添加到order_info表中
            JSONObject data = result.getJSONObject("data");
            //设置添加数据--就诊人数据
            //订单号
            String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setHoscode(scheduleOrderVo.getHoscode());
            orderInfo.setUserId(patient.getUserId());
            orderInfo.setHosname(scheduleOrderVo.getHosname());
            orderInfo.setDepcode(scheduleOrderVo.getDepcode());
            orderInfo.setDepname(scheduleOrderVo.getDepname());
            orderInfo.setTitle(scheduleOrderVo.getTitle());
            orderInfo.setReserveDate(scheduleOrderVo.getReserveDate());
            orderInfo.setReserveTime(scheduleOrderVo.getReserveTime());
            orderInfo.setScheduleId(scheduleId);
            orderInfo.setPatientId(patient.getId());
            orderInfo.setPatientName(patient.getName());
            orderInfo.setAmount(scheduleOrderVo.getAmount());
            orderInfo.setQuitTime(scheduleOrderVo.getQuitTime());//退号时间
            orderInfo.setPatientPhone(patient.getPhone());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            baseMapper.insert(orderInfo);
            //3.3更新平台上对应医生的剩余可预约数
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = data.getString("hosRecordId");
            //预约序号
            Integer number = data.getInteger("number");;
            //取号时间
            String fetchTime = data.getString("fetchTime");;
            //取号地址
            String fetchAddress = data.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = data.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = data.getInteger("availableNumber");
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            MsmVo smsVo = new MsmVo();
            smsVo.setPhone(patient.getPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            smsVo.setTemplate("您已经预约了"+reserveDate+"的预约号，不要迟到！");
            orderMqVo.setMsmVo(smsVo);
            //发送mq信息更新号源和短信通知
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
        }else {
            //下单失败
            //3.1如果返回不能挂号，直接抛出异常
            throw new YyghException(20001,"号源已满");
        }
        //4.返回订单的id
        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.packOrderInfo(orderInfo);
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
       //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    /**
     *  取消订单
     * @param orderId
     * @return
     */
    @Override
    public Boolean cancelOrder(Long orderId) {
        //1.确定当前取消预约的时间 和 挂号订单的取消预约截止时间 对比，当前时间是否已经超过了 挂号订单的取消预约截山吖问:
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        //挂号订单的取消预约截止时间
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if (quitTime.isBeforeNow()){
            //如果超过了，直接抛出异常，不让用户取消
            System.out.println(111);
            throw new YyghException(20001,"已经超过取消时间");
        }else {
        //如果没有超过，往下执行
        //2.从平台请求第三方医院，通知第三方医院，该用户已取消
        HashMap<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, "http://localhost:9998/order/updateCancelStatus");
        if (result.getInteger("code") != 200){
            // 2.1 第三方医院如果不同意取消:抛出异常，不能取消
            throw new YyghException(20001,"请求第三方医院取消失败");
        }
        // 2.2 第三方医院如果同意取消: 继续执行
        //3.判断用户是否对当前挂号订单是否已支付
        if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus()){
            //3.1.如果已支付，退款
            boolean isRefund = weiPayService.refund(orderId);
            if(!isRefund) {
                throw new YyghException();
            }
        }
        //3.2 如果未支付，继续往下执行
        //更改订单状态
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);
        //更新支付记录状态。
        QueryWrapper<PaymentInfo> queryWrapper=new QueryWrapper<PaymentInfo>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentService.getOne(queryWrapper);
        paymentInfo.setPaymentStatus(PaymentStatusEnum.REFUND.getStatus()); //退款
        paymentInfo.setUpdateTime(new Date());
        paymentService.updateById(paymentInfo);
        //5.更新医生的剩余可预约数信息
        //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        //6.给就诊人发送短信提示:
        //短信提示
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        orderMqVo.setMsmVo(msmVo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
    }
        return true;
    }

    @Override
    public void patientRemind() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for(OrderInfo orderInfo : orderInfoList) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS, MqConst.ROUTING_SMS_ITEM, msmVo);
        }
    }

    @Override
    public Map<String, Object> statistics(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> countVoList = baseMapper.statistics(orderCountQueryVo);
        ArrayList<String> dateList = new ArrayList<String>();
        ArrayList<Integer> countList = new ArrayList<Integer>();
        for (OrderCountVo orderCountVo : countVoList) {
            String reserveDate = orderCountVo.getReserveDate();
            Integer count = orderCountVo.getCount();
            dateList.add(reserveDate);
            countList.add(count);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}
